<template>
	<div :class="['app-editor-container', 'app-rating', `app-rating-${name}`]">
		<a-rate
			:value="value"
			:allowHalf="allowHalf"
			:count="maxItem"
			:tooltips="texts"
			:disabled="disabled || readOnly"
			@change="onChange"
			@blur="onBlur"
			@focus="onFocus"
		/>
	</div>
</template>

<script setup lang="ts">
import { IEvent } from '@/core';
import { ratingProps } from './rating';
import { handleEditorNavParams, useEditorTypeParams } from '@/hooks/use-editor';
interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(ratingProps);
const emit = defineEmits<EditorEmit>();
// 类型校验
const { validateConfig } = useEditorTypeParams();
validateConfig();
const { navContext, navViewParam } = handleEditorNavParams(props);
let maxItem = toRef(props, 'max');
let data = toRef(props, 'data');
const onChange = (value: number) => {
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: value,
	});
};
const onBlur = () => {
	emit('component-action', {
		name: `${props.name}`,
		action: 'editorBlur',
		data: props.value,
	});
};
const onFocus = () => {
	emit('component-action', {
		name: `${props.name}`,
		action: 'editorFocus',
		data: props.value,
	});
};

onBeforeMount(() => {
	loadData();
});

watch(
	() => data,
	(newVal: any, oldVal: any) => {
		if (props.codeListTag && props.codeListType == 'DYNAMIC') {
			loadData();
		}
	},
	{
		immediate: true,
		deep: true,
	}
);

const loadData = async () => {
	if (props.codeListTag && props.codeListType) {
		const items = await App.getAppCodeListHelper()
			.getCodeListItems(props.codeListTag, navContext, navViewParam)
			.then((codelistResult: any) => {
				if (codelistResult.ok) {
					const codeListItems = codelistResult.data;
					const maxCodeListItem = Math.max.apply(
						Math,
						codeListItems.map((item: any) => {
							return item.value;
						})
					);
					maxItem.value = maxCodeListItem > 5 ? 5 : maxItem.value;
				}
			})
			.catch((error: any) => {
				App.getNotificationHelper().error(
					App.ts('common.generic.error', '错误'),
					App.ts('common.generic.codenotexist', '代码表不存在')
				);
			});
	}
};
</script>
